#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
添加更多示例数据
包括作业提交记录、系统日志等
"""

import sys
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from app import create_app
from models import db, User, Class, Problem, Assignment, AssignmentSubmission, SystemLog
from datetime import datetime, timedelta
import json
import random

def add_sample_data():
    """添加示例数据"""
    app = create_app()
    with app.app_context():
        print("开始添加示例数据...")
        
        # 添加作业提交记录
        create_sample_submissions()
        
        # 添加系统日志
        create_sample_logs()
        
        # 添加更多学生
        create_more_students()
        
        print("✓ 示例数据添加完成！")

def create_sample_submissions():
    """创建示例作业提交记录"""
    # 获取作业和学生
    assignments = Assignment.query.all()
    students = User.query.filter_by(role='student').all()
    problems = Problem.query.all()
    
    if not assignments or not students or not problems:
        print("⚠ 没有找到作业、学生或题目数据")
        return
    
    submissions = []
    
    # 为每个作业创建一些提交记录
    for assignment in assignments:
        assignment_students = assignment.class_obj.students
        assignment_problems = json.loads(assignment.problem_ids)
        
        for student in assignment_students:
            # 随机选择一些题目进行提交
            for problem_id in random.sample(assignment_problems, min(2, len(assignment_problems))):
                problem = Problem.query.get(problem_id)
                if not problem:
                    continue
                
                # 随机生成提交状态
                statuses = ['accepted', 'wrong_answer', 'time_limit', 'compile_error', 'pending']
                status = random.choice(statuses)
                
                # 根据状态生成分数
                if status == 'accepted':
                    score = random.randint(80, 100)
                elif status == 'wrong_answer':
                    score = random.randint(0, 30)
                else:
                    score = 0
                
                # 生成提交时间（在作业创建时间之后，截止时间之前）
                submit_time = assignment.created_at + timedelta(
                    days=random.randint(1, 5),
                    hours=random.randint(0, 23),
                    minutes=random.randint(0, 59)
                )
                
                # 生成示例代码
                sample_code = generate_sample_code(problem.title)
                
                submission = AssignmentSubmission(
                    assignment_id=assignment.id,
                    student_id=student.id,
                    problem_id=problem_id,
                    code=sample_code,
                    language='python',
                    status=status,
                    score=score,
                    submitted_at=submit_time
                )
                
                submissions.append(submission)
    
    # 批量添加提交记录
    for submission in submissions:
        db.session.add(submission)
    
    db.session.commit()
    print(f"✓ 创建了 {len(submissions)} 个作业提交记录")

def generate_sample_code(problem_title):
    """根据题目生成示例代码"""
    code_samples = {
        '两数之和': '''def twoSum(nums, target):
    hash_map = {}
    for i, num in enumerate(nums):
        complement = target - num
        if complement in hash_map:
            return [hash_map[complement], i]
        hash_map[num] = i
    return []

# 测试
nums = [2, 7, 11, 15]
target = 9
result = twoSum(nums, target)
print(result)''',
        
        '反转字符串': '''def reverseString(s):
    left, right = 0, len(s) - 1
    while left < right:
        s[left], s[right] = s[right], s[left]
        left += 1
        right -= 1
    return s

# 测试
s = list("hello")
result = reverseString(s)
print(''.join(result))''',
        
        '最大子数组和': '''def maxSubArray(nums):
    max_sum = current_sum = nums[0]
    for num in nums[1:]:
        current_sum = max(num, current_sum + num)
        max_sum = max(max_sum, current_sum)
    return max_sum

# 测试
nums = [-2, 1, -3, 4, -1]
result = maxSubArray(nums)
print(result)''',
        
        '合并两个有序链表': '''class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def mergeTwoLists(l1, l2):
    if not l1:
        return l2
    if not l2:
        return l1
    
    if l1.val <= l2.val:
        l1.next = mergeTwoLists(l1.next, l2)
        return l1
    else:
        l2.next = mergeTwoLists(l1, l2.next)
        return l2''',
        
        '有效的括号': '''def isValid(s):
    stack = []
    brackets = {')': '(', '}': '{', ']': '['}
    
    for char in s:
        if char in '({[':
            stack.append(char)
        else:
            if not stack or stack.pop() != brackets[char]:
                return False
    
    return len(stack) == 0

# 测试
s = "()[]{}"
result = isValid(s)
print(result)''',
        
        '爬楼梯': '''def climbStairs(n):
    if n <= 2:
        return n
    
    dp = [0] * (n + 1)
    dp[1] = 1
    dp[2] = 2
    
    for i in range(3, n + 1):
        dp[i] = dp[i-1] + dp[i-2]
    
    return dp[n]

# 测试
n = 3
result = climbStairs(n)
print(result)'''
    }
    
    return code_samples.get(problem_title, '# 示例代码\nprint("Hello, World!")')

def create_sample_logs():
    """创建示例系统日志"""
    users = User.query.all()
    
    log_messages = [
        ('info', '用户登录系统'),
        ('info', '用户查看题目列表'),
        ('info', '用户提交作业'),
        ('success', '作业提交成功'),
        ('warning', '作业提交超时'),
        ('error', '代码编译错误'),
        ('info', '教师批改作业'),
        ('success', '作业批改完成'),
        ('info', '创建新班级'),
        ('info', '添加学生到班级'),
        ('info', '创建新作业'),
        ('info', '查看班级统计'),
        ('info', '导出作业报告'),
        ('error', '数据库连接失败'),
        ('warning', '系统资源使用率较高')
    ]
    
    logs = []
    for _ in range(50):  # 创建50条日志
        log_type, base_message = random.choice(log_messages)
        user = random.choice(users) if random.random() > 0.3 else None  # 30%的日志没有用户
        
        # 根据日志类型生成具体消息
        if '用户登录' in base_message:
            message = f"用户 {user.name if user else '未知'} 登录系统"
        elif '用户查看' in base_message:
            message = f"用户 {user.name if user else '未知'} 查看了题目列表"
        elif '用户提交' in base_message:
            message = f"用户 {user.name if user else '未知'} 提交了作业"
        elif '作业提交成功' in base_message:
            message = f"作业提交成功，学生: {user.name if user else '未知'}"
        elif '作业提交超时' in base_message:
            message = f"作业提交超时，学生: {user.name if user else '未知'}"
        elif '代码编译错误' in base_message:
            message = f"代码编译错误，学生: {user.name if user else '未知'}"
        elif '教师批改' in base_message:
            message = f"教师 {user.name if user else '未知'} 批改了作业"
        elif '作业批改完成' in base_message:
            message = f"作业批改完成，教师: {user.name if user else '未知'}"
        elif '创建新班级' in base_message:
            message = f"教师 {user.name if user else '未知'} 创建了新班级"
        elif '添加学生' in base_message:
            message = f"教师 {user.name if user else '未知'} 添加学生到班级"
        elif '创建新作业' in base_message:
            message = f"教师 {user.name if user else '未知'} 创建了新作业"
        elif '查看班级统计' in base_message:
            message = f"教师 {user.name if user else '未知'} 查看了班级统计"
        elif '导出作业报告' in base_message:
            message = f"教师 {user.name if user else '未知'} 导出了作业报告"
        else:
            message = base_message
        
        # 生成随机时间（最近30天内）
        log_time = datetime.now() - timedelta(
            days=random.randint(0, 30),
            hours=random.randint(0, 23),
            minutes=random.randint(0, 59)
        )
        
        log = SystemLog(
            type=log_type,
            message=message,
            user_id=user.id if user else None,
            ip_address=f"192.168.1.{random.randint(1, 255)}",
            created_at=log_time
        )
        
        logs.append(log)
    
    # 批量添加日志
    for log in logs:
        db.session.add(log)
    
    db.session.commit()
    print(f"✓ 创建了 {len(logs)} 条系统日志")

def create_more_students():
    """创建更多学生用户"""
    existing_students = User.query.filter_by(role='student').count()
    
    if existing_students >= 10:
        print(f"✓ 已有 {existing_students} 个学生，跳过创建更多学生")
        return
    
    new_students = []
    student_names = [
        '陈八', '孙九', '周十', '吴十一', '郑十二',
        '王十三', '冯十四', '陈十五', '褚十六', '卫十七',
        '蒋十八', '沈十九', '韩二十', '杨二一', '朱二二',
        '秦二三', '尤二四', '许二五', '何二六', '吕二七'
    ]
    
    for i, name in enumerate(student_names[existing_students:10], existing_students + 1):
        student = User(
            username=f'student{i}',
            password='student123',
            name=name,
            email=f'student{i}@oj.com',
            role='student'
        )
        new_students.append(student)
    
    # 批量添加学生
    for student in new_students:
        db.session.add(student)
    
    db.session.commit()
    print(f"✓ 创建了 {len(new_students)} 个新学生")
    
    # 随机将新学生分配到班级
    classes = Class.query.all()
    new_students = User.query.filter_by(role='student').all()[existing_students:]
    
    for student in new_students:
        # 随机分配到1-2个班级
        num_classes = random.randint(1, min(2, len(classes)))
        selected_classes = random.sample(classes, num_classes)
        
        for class_obj in selected_classes:
            if len(class_obj.students) < class_obj.max_students:
                class_obj.students.append(student)
    
    db.session.commit()
    print(f"✓ 将新学生分配到班级")

if __name__ == '__main__':
    add_sample_data()
